#encoding=utf-8
import requests,json,mysqldb,random
import base64,baseFunc

class base_web():
    def _get_web_data(self,url,params=None,headers=None):
        if url.find('http')<0:
            surl='http://'+url
        else:
            surl=url
        try:
            response = requests.get(surl,params=params,headers=headers)
            data=response.text
            state=str(response.status_code)
            response.close()
        except Exception, e:
            data = None
            state = str(e)
        return state,data
    def _post_web_data(self,url,params=[],heads='',cookies=''):
        if url.find('http')<0:
            surl='http://'+url
        else:
            surl=url
        state='200'
        try:
            response = requests.post(surl,data=params,headers=heads,cookies=cookies)
            data=response.text
            cookies=response.cookies
            response.close()
            if not response.status_code==200:
                return str(response.status_code),data,''
        except Exception, e:
            data = None
            cookies=None
            state = str(e)
        return state,data,cookies
    def check_is_head(self,imgurl):
        mdata=self._get_web_data('https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' %
                        ('YnFQidkcxLZ3bQYwDeI3TjTo','g8jR7ff7HM3UW3VlSe7xWFNywYAM0p3A'))
        if mdata[0]=='200':
            try:
                mjson=json.loads(mdata[1])
            except:
                return False
            rdata= self._get_web_data('https://openapi.baidu.com/rest/2.0/media/v1/face/detect?access_token=%s&url=%s' %\
                                   (mjson.get('access_token'),
                                    imgurl))
            if rdata[0]=='200':
                try:
                    rjson=json.loads(rdata[1])
                    if len(rjson.get('face'))>0:
                        return True
                except:
                    return False
        return False
